package print_table_columns;

require Exporter;


our @ISA = qw(Exporter);
our $VERSION = 1.00;
our @EXPORT = qw(prepare_column_headers);



use strict;
use warnings;
use Carp;
#_________________________________________________________________________________________

#	prepare_column_headers

#		print column headers
#		return format string to print values according to column header and specialized format strings

#_________________________________________________________________________________________
sub prepare_column_headers($\@\@)
{
	my ($PH, $column_names, $output_formats) = @_;

	# check the two lists are of the same sizes
	croak "Error:\n\tColumn names and output formats are of different sizes (".
		scalar @$column_names. ",". scalar @$output_formats . ").\n "
		unless scalar @$column_names == scalar @$output_formats;

	my @orig_len = map{length($_)} @$column_names;
	my @format_str_len = map
	{
		/(\d+)/ or croak "Error:\n\tInvalid format string\n( $_ )";
		$1;
	} @$output_formats;
	my @len = @orig_len;
	for my $i(0 .. $#len)
	{
		if ($len[$i] < $format_str_len[$i])
		{
			$len[$i] = $format_str_len[$i];
		}
	}

	# print names
	{
		my @format_strings;
		for my $i (0.. $#len)
		{
			my $half_padding = int(($len[$i] - $orig_len[$i]) / 2);
			my $before = (' ' x $half_padding);
			my $after = (' ' x ($len[$i] - $orig_len[$i] - $half_padding));
			push(@format_strings,  $before . "%-$orig_len[$i]s" . $after);
		}
		my $format_line =  join (" | ",  @format_strings)."\n";
		printf $PH $format_line, @$column_names;
	}


	# print underlines
	{
		my $format_line = join (" + ", map{"%-".$_."s"} @len) . "\n";
		printf $PH $format_line, map{"-" x $_} @len;
	}

	my @format_strings;
	for my $i (0.. $#len)
	{
		my $half_padding = int(($len[$i] - $format_str_len[$i]) / 2);
		my $before = (' ' x $half_padding);
		my $after = (' ' x ($len[$i] - $format_str_len[$i] - $half_padding));

		# print STDERR "<$before><$after>\n";
		push(@format_strings,  $before . $output_formats->[$i] . $after);
	}
	return join (" | ",  @format_strings)."\n";
}



1;
